import * as React from 'react';
import { withRouter, RouteComponentProps } from 'react-router';
import { Link } from 'react-router-dom';

import { Container } from '../../components/layout';
import { Markdown } from '../../components/markdown';

import Apis from '../../apis';
import { Post } from '../../models/post';

type PropsType = RouteComponentProps<{ postId: string }> & {};

type StatesType = {
  post?: Post;
  loading: boolean;
};

class PostPage extends React.Component<PropsType> {
  state: StatesType = {
    loading: true,
    post: undefined,
  };

  async componentDidMount() {
    await this.loadPost();
  }

  async loadPost() {
    this.setState({ loading: true });
    const post = await Apis.Post.getPost(+this.props.match.params.postId);
    this.setState({ post, loading: false });
  }

  render() {
    const { post, loading } = this.state;
    if (loading) {
      return <div>加载中...</div>;
    }

    return (
      <Container>
        <header>
          <h1
            style={{
              display: 'block',
              fontSize: '2.5rem',
              fontWeight: 'bolder',
              marginTop: '2rem',
              borderBottom: '3px solid red',
            }}
          >
            {post.title}
            <small style={{ fontSize: '0.8rem' }}>
              <Link to={`/post/edit/${post.postId}`}>编辑</Link>
            </small>
          </h1>
        </header>

        <main>
          <Markdown md={post.content} />
        </main>
      </Container>
    );
  }
}

export default withRouter(PostPage);
